var api = require("../../api.js"), app = getApp(), share_count = 0, width = 260, int = 1, interval = 0, page_first_init = !0, timer = 1, msgHistory = "", fullScreen = !1;

Page({
    data: {
        x: wx.getSystemInfoSync().windowWidth,
        y: wx.getSystemInfoSync().windowHeight,
        left: 0,
        show_notice: !1,
        animationData: {},
        play: -1,
        time: 0,
        buy_user: "",
        buy_address: "",
        buy_time: 0,
        num : 0,
        buy_type: ""
    },
    onLoad: function(t) {
        app.pageOnLoad(this), this.loadData(t),this.getShop(t),this.tuanKeTime();
        var a = 0, e = t.user_id, i = decodeURIComponent(t.scene);
        wx.showLoading({
            title: "加载中"
        });
        this.loadTopicList({
            page: 1,
            reload: !0
        });
        null != e ? a = e : null != i && (a = i), app.loginBindParent({
            parent_id: a
        });
    },

    loadTopicList: function(i) {
        var r = this, arr=[], page = 1 , state = 0 ;
         app.request({
            url: api.default.topic_type,
            data: {},
            success: function(a) {
                if (0 == a.code) {
                    for(var i in a.data.list){
                        if(a.data.list[i].name.indexOf('教练')>=0){
                            arr = a.data.list[i];
                            state = 1;
                            app.request({
                                url: api.default.topic_list,
                                data: {
                                    page: page,
                                    type: arr.id,
                                },
                                success: function(a) {             
                                  0 == a.code && r.setData({
                                    coachArr : a.data.list
                                   })
                                }
                            });
                        }
                    }
                    r.setData({
                        navbarArray: arr,
                        state:state,
                    })
                }
            }
        });
    },
    topicList: function(e) {
        wx.navigateTo({
            url: '/pages/topic-list/topic-list?type='+ this.data.navbarArray.id,
          })
    },
    getGoodList:function(e) {
        wx.navigateTo({
            url: '/pages/goods/goods?id='+ e.target.dataset.id,
          })
    },
    getUserInfo: function(o) {
        "getUserInfo:ok" == o.detail.errMsg && (wx.showLoading({
            title: "正在登录",
            mask: !0
        }), wx.login({
            success: function(e) {
                var t = e.code;
                app.request({
                    url: api.passport.login,
                    method: "POST",
                    data: {
                        code: t,
                        user_info: o.detail.rawData,
                        encrypted_data: o.detail.encryptedData,
                        iv: o.detail.iv,
                        signature: o.detail.signature
                    },
                    success: function(e) {
                        if (0 == e.code) {
                            wx.setStorageSync("access_token", e.data.access_token), wx.setStorageSync("user_info", e.data);
                             wx.redirectTo({
                                url: "/pages/index/index"
                            });
                            
                        } else wx.showModal({
                            title: "提示",
                            content: e.msg,
                            showCancel: !1
                        });
                    },
                    complete: function() {
                        wx.hideLoading();
                    }
                });
            },
            fail: function(e) {}
        }));
    },

    getPhoneNumber: function(e) {
        var a = this;
         "getPhoneNumber:fail user deny" == e.detail.errMsg ? wx.showModal({
            title: "提示",
            showCancel: !1,
            content: "未授权",
            success: function(n) {}
        }) : (wx.showLoading({
            title: "授权中"
        }), wx.login({
            success: function(n) {
                if (n.code) {
                    var t = n.code;
                    app.request({
                        url: api.user.user_binding,
                        method: "POST",
                        data: {
                            iv: e.detail.iv,
                            encryptedData: e.detail.encryptedData,
                            code: t
                        },
                        success: function(n) {
                            if (0 == n.code) {
                                var t = a.data.__user_info;
                                t.binding = n.data.dataObj, wx.setStorageSync("user_info", t), a.setData({
                                    PhoneNumber: n.data.dataObj,
                                    __user_info: t,
                                    binding: !0,
                                    binding_num: n.data.dataObj
                                });
                                wx.hideLoading();
                                wx.navigateTo({
                                    url: '/pages/goods/goods?id='+ e.target.dataset.id,
                                  });
                            } else wx.showToast({
                                title: "授权失败,请重试"
                            });
                        },
                        fail: function(n) {
                            wx.hideLoading();
                        }
                    });
                } else wx.showToast({
                    title: "获取用户登录态失败！" + n.errMsg,
                    image: "/images/icon-warning.png"
                });
            }
        }));
    },
    getShop: function(e) {
        var r = this;
        app.request({
            url: api.default.shop_list,
            method: "GET",
            data: {
                longitude: 0,
                latitude: 0
            },
            success: function(t) {
                if(0 == t.code){
                    for(var i in t.data.list) {                        
                        if(t.data.list[i].is_default == '1') {   
                            var id = t.data.list[i].id;           
                        }
                    }
                  r.getShoplist(id)
                }
               
            },
         
        });
    },
    getShoplist: function (id) {
        var r=this;
        app.request({
            url: api.default.shop_detail,
            method: "GET",
            data: {
                shop_id: id
            },
            success: function(t) {
                if( 0 == t.code){
                    r.setData({
                        venueArr: t.data.shop
                    })      
                }
                 
            }
        });    
    },
    onClickSijiao: function(e) {
        wx.navigateTo({
            url: '/pages/topic/topic?id='+ e.currentTarget.dataset.id,
          })
        
    },
    suspension: function() {
        var r = this;
        interval = setInterval(function() {
            app.request({
                url: api.default.buy_data,
                data: {
                    time: r.data.time
                },
                method: "POST",
                success: function(t) {
                    if (0 == t.code) {
                        var a = !1;
                        msgHistory == t.md5 && (a = !0);
                        var e = "", i = t.cha_time, n = Math.floor(i / 60 - 60 * Math.floor(i / 3600));
                        e = 0 == n ? i % 60 + "秒" : n + "分" + i % 60 + "秒";
                        var o = "购买了", s = "/pages/goods/goods?id=" + t.data.goods;
                        2 === t.data.type ? (o = "预约了", s = "/pages/book/details/details?id=" + t.data.goods) : 3 === t.data.type ? (o = "秒杀了", 
                        s = "/pages/miaosha/details/details?id=" + t.data.goods) : 4 === t.data.type && (o = "拼团了", 
                        s = "/pages/pt/details/details?gid=" + t.data.goods), !a && t.cha_time <= 300 ? (r.setData({
                            buy_time: e,
                            buy_type: o,
                            buy_url: s,
                            buy_user: 5 <= t.data.user.length ? t.data.user.slice(0, 4) + "..." : t.data.user,
                            buy_avatar_url: t.data.avatar_url,
                            buy_address: 8 <= t.data.address.length ? t.data.address.slice(0, 7) + "..." : t.data.address
                        }), msgHistory = t.md5) : r.setData({
                            buy_user: "",
                            buy_type: "",
                            buy_url: s,
                            buy_address: "",
                            buy_avatar_url: "",
                            buy_time: ""
                        });
                    }
                }
            });
        }, 1e4);
    },
    tuanKeTime: function() {
        var a = this;
        app.request({
            url: api.miaosha.list,
            success: function(t) {
                if (0 == t.code) {
                    for(var i in t.data.list) {
                        switch(t.data.list[i].status_text){
                            case "已结束":
                            t.data.list[i].status_text_status = "pt-end";
                                break;
                            case "进行中":
                            t.data.list[i].status_text_status = "pt-start";
                                break;
                            case "即将开始":
                            t.data.list[i].status_text_status = "pt-not";
                                break;     
                        }; 
                         t.data.list[i].time_len = Math.round((t.data.list[i].end_time - t.data.list[i].begin_time) % 3600 / 60) + "分钟";
                    };
                    a.setData({
                        time_list: t.data.list
                    }),a.tuanKeList();
                }
            }
        })
    },
    tuanKeList:function() {
        var a = this,arr=[];
        for(var i in a.data.time_list){
            var t = a.data.time_list[i].start_time;
            var id = a.data.time_list[i].id;
            app.request({
                url: api.miaosha.details,
                data: {
                    time:t,
                    id:id,
                },
                success: function(t) {
                    if(0 == t.code){
                         arr.push(t.data)
                    }
                    a.setData({
                        arr:arr
                    })
                },
                complete: function() {
                    wx.hideLoading();
                    var o = wx.getStorageSync("user_info");
                    if(!o){
                        a.setData({
                         hiddenScroll:!0
                        })
                    }else{
                     a.setData({
                         hiddenScroll:!1
                        })
                    }
                }
            })
        }

    },
    getActiveGoods: function(e) {
        var a = this;
        app.request({
            url: api.default.goods,
            data: {
                id: a.data.active.goods_list[0].id
            },
            success: function(t) {
                console.log(t)
                if(0 == t.code){
                    a.setData({
                        ActiveGoods : t.data
                    })
                }                
            }
        })
    },
    gotcList: function(e) {
        wx.navigateTo({
            url: '/pages/miaosha/details/details?id='+ e.currentTarget.dataset.id + "&statu=" + e.currentTarget.dataset.status,
          })
    },
    loadData: function(t) {
        var s = this, a = wx.getStorageSync("pages_index_index"),active = [];
        a && (a.act_modal_list = [], s.setData(a)), app.request({
            url: api.default.index,
            success: function(t) {
                if (0 == t.code) {
                    console.log(t)
                    var module_list = t.data.module_list.sort();
                    var cat_list = t.data.cat_list.sort();
                    for(let i in module_list) {
                        if(module_list[i].name == "search") {
                            s.data.num++;
                        }             
                    }
                    if(s.data.num % 2 == 1) {
                        s.setData({
                            showState : 1
                        })
                    }else {
                        s.setData({
                            showState : 2
                        })
                    }     
                    for(let i in cat_list){
                        if(cat_list[i].name == '活动'){
                            active = cat_list[i]
                        }
                    }       
                    s.setData({
                        active : active
                    })      
                    s.getActiveGoods();
                    wx.setStorageSync('active',active);  
                    console.log(active)
                    page_first_init ? page_first_init = !1 : t.data.act_modal_list = [];
                    var a = t.data.topic_list, e = new Array();
                    if (a && 1 != t.data.update_list.topic.count) {
                        if (1 == a.length) e[0] = new Array(), e[0] = a; else for (var i = 0, n = 0; i < a.length; i += 2, 
                        n++) null != a[i + 1] && (e[n] = new Array(), e[n][0] = a[i], e[n][1] = a[i + 1]);
                        t.data.topic_list = e;
                    }
                    s.setData(t.data), wx.setStorageSync("store", t.data.store), wx.setStorageSync("pages_index_index", t.data);
                    var o = wx.getStorageSync("user_info");
                    o && s.setData({
                        _user_info: o                       
                    }),s.miaoshaTimer();
                }
            },
            complete: function() {
                wx.stopPullDownRefresh();                                
            }
        });
    },
    onShow: function() {        
        app.pageOnShow(this), share_count = 0;
        var t = wx.getStorageSync("store");
        var o = wx.getStorageSync("user_info");
            o && o.binding ? this.setData({
                binding: !0
            }) : this.setData({
                binding: !1
            });
        t && t.name && wx.setNavigationBarTitle({
            title: t.name
        }), 1 === t.purchase_frame ? this.suspension(this.data.time) : this.setData({
            buy_user: ""
        }), clearInterval(int), this.notice();

    },
    onPullDownRefresh: function() {
        clearInterval(timer), this.loadData();
    },
    onShareAppMessage: function(t) {        
        var a = this;
        return {
            // imageUrl: a.data.active.goods_list[0].pic_url,
            path: "/pages/index/index?user_id=" + wx.getStorageSync("user_info").id,
            success: function(t) {
                1 == ++share_count && app.shareSendCoupon(a);
            },
            title: a.data.store.name
            
        };
    },
    receive: function(t) {
        var e = this, a = t.currentTarget.dataset.index;
        wx.showLoading({
            title: "领取中",
            mask: !0
        }), e.hideGetCoupon || (e.hideGetCoupon = function(t) {
            var a = t.currentTarget.dataset.url || !1;
            e.setData({
                get_coupon_list: null
            }), a && wx.navigateTo({
                url: a
            });
        }), app.request({
            url: api.coupon.receive,
            data: {
                id: a
            },
            success: function(t) {
                wx.hideLoading(), 0 == t.code ? e.setData({
                    get_coupon_list: t.data.list,
                    coupon_list: t.data.coupon_list
                }) : (wx.showToast({
                    title: t.msg,
                    duration: 2e3
                }), e.setData({
                    coupon_list: t.data.coupon_list
                }));
            }
        });
    },
    navigatorClick: function(t) {
        var a = t.currentTarget.dataset.open_type, e = t.currentTarget.dataset.url;
        return "wxapp" != a || ((e = function(t) {
            var a = /([^&=]+)=([\w\W]*?)(&|$|#)/g, e = /^[^\?]+\?([\w\W]+)$/.exec(t), i = {};
            if (e && e[1]) for (var n, o = e[1]; null != (n = a.exec(o)); ) i[n[1]] = n[2];
            return i;
        }(e)).path = e.path ? decodeURIComponent(e.path) : "", 
        wx.navigateToMiniProgram({
            appId: e.appId,
            path: e.path,
            complete: function(t) {
            }
        }), !1);
    },
    getPhoneClick: function(e) {
        wx.makePhoneCall({
            phoneNumber: e.target.dataset.phone,
          })
    },
    navigatorImgClick:function(e) {
        var a=[], src=e.target.dataset.src; 
        a.push(src);
        wx.previewImage({
            urls: this.data.venueArr.pic_list,
            current: src
        });
    },
    closeCouponBox: function(t) {
        this.setData({
            get_coupon_list: ""
        });
    },
    notice: function() {
        var t = this.data.notice;
        if (null != t) t.length;
    },
    miaoshaTimer: function() {
        var t = this;
        t.data.miaosha && t.data.miaosha.rest_time && (timer = setInterval(function() {
            0 < t.data.miaosha.rest_time ? (t.data.miaosha.rest_time = t.data.miaosha.rest_time - 1, 
            t.data.miaosha.times = t.getTimesBySecond(t.data.miaosha.rest_time), t.setData({
                miaosha: t.data.miaosha
            })) : clearInterval(timer);
        }, 1e3));
    },
    onHide: function() {
        app.pageOnHide(this), this.setData({
            play: -1
        }), clearInterval(int), clearInterval(interval);
    },
    onUnload: function() {
        app.pageOnUnload(this), this.setData({
            play: -1
        }), clearInterval(timer), clearInterval(int), clearInterval(interval);
    },
    showNotice: function() {
        this.setData({
            show_notice: !0
        });
    },
    closeNotice: function() {
        this.setData({
            show_notice: !1
        });
    },
    getTimesBySecond: function(t) {
        if (t = parseInt(t), isNaN(t)) return {
            h: "00",
            m: "00",
            s: "00"
        };
        var a = parseInt(t / 3600), e = parseInt(t % 3600 / 60), i = t % 60;
        return 1 <= a && (a -= 1), {
            h: a < 10 ? "0" + a : "" + a,
            m: e < 10 ? "0" + e : "" + e,
            s: i < 10 ? "0" + i : "" + i
        };
    },
    to_dial: function() {
        var t = this.data.store.contact_tel;
        wx.makePhoneCall({
            phoneNumber: t
        });
    },
    closeActModal: function() {
        var t, a = this, e = a.data.act_modal_list, i = !0;
        for (var n in e) {
            var o = parseInt(n);
            e[o].show && (e[o].show = !1, void 0 !== e[t = o + 1] && i && (i = !1, setTimeout(function() {
                a.data.act_modal_list[t].show = !0, a.setData({
                    act_modal_list: a.data.act_modal_list
                });
            }, 500)));
        }
        a.setData({
            act_modal_list: e
        });
    },
    naveClick: function(t) {
        app.navigatorClick(t, this);
    },
    play: function(t) {
        this.setData({
            play: t.currentTarget.dataset.index
        });
    },
    onPageScroll: function(t) {
        var e = this;
        fullScreen || -1 != e.data.play && wx.createSelectorQuery().select(".video").fields({
            rect: !0
        }, function(t) {
            var a = wx.getSystemInfoSync().windowHeight;
            (t.top <= -200 || t.top >= a - 57) && e.setData({
                play: -1
            });
        }).exec();
    },
    fullscreenchange: function(t) {
        fullScreen = !!t.detail.fullScreen;
    },
    showShareModal: function() {
        this.setData({
            share_modal_active: "active",
            no_scroll: !0,
            hiddenScroll: !0
        });
    },
    shareModalClose: function() {
        this.setData({
            share_modal_active: "",
            no_scroll: !1,
            hiddenScroll: !1
        });
    },
    getGoodsQrcode: function() {
        var a = this;
        console.log(a.data.active.goods_list[0])
        if (a.setData({
            goods_qrcode_active: "active",
            share_modal_active: ""
        }), a.data.goods_qrcode) return !0;
        app.request({
            url: api.default.goods_qrcode,
            data: {
                goods_id: a.data.active.id
            },
            success: function(t) {
                console.log(t)
                0 == t.code && a.setData({
                    goods_qrcode: t.data.pic_url
                }), 1 == t.code && (a.goodsQrcodeClose(), wx.showModal({
                    title: "提示",
                    content: t.msg,
                    showCancel: !1,
                    success: function(t) {
                        t.confirm;
                    }
                }));
            }
        });
    },
    goodsQrcodeClose: function() {
        this.setData({
            goods_qrcode_active: "",
            no_scroll: !1,
            hiddenScroll: !1
        });
    },
    onClickshare: function() {
        this.setData({
            goods_qrcode_active: "",
            no_scroll: !1,
            hiddenScroll: !1
        });
    },
});